package action.bookinfo;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import bizlogic.bookinfo.BookInfoService;
import bizlogic.bookinfo.domain.BookInfo;

@WebServlet("/bookinfolistaction")
public class BookInfoListAction extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    BookInfoService bookInfoService = new BookInfoService();


  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if ("queryBookInfo".equals(request.getParameter("method"))) {
            queryBookInfo(request, response);
        }
        if ("deleteBookInfo".equals(request.getParameter("method"))) {
            deleteBookInfo(request, response);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);

    }

    /*
     * 功能需求：能够根据ids值调用service相关方法删除数据（ids是多个id的以“，”拼接）；
     */
    public void deleteBookInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookIds = request.getParameter("bookids");
        String string = bookInfoService.deleteBookInfoByBookId(bookIds);
        response.getWriter().write(string);
    }

    /*
     * 功能需求：能够根据pageIndex、pageSize、bookName、bookType查询图书信息
     */
    public HashMap<String, Object> queryBookInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookName = request.getParameter("bookName");
        String bookType = request.getParameter("bookType");
        // 判断booktype是否为空，只用不为空才能转化为int
        Integer bookTypevalue = null;
        if ((!"".equals(bookType)) && bookType != null) {
            bookTypevalue = Integer.parseInt(bookType);
        }
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        // 一个列表展示信息
        List<BookInfo> queryBookinfoByKeyWordsInPage = bookInfoService.queryBookinfoByKeyWords(pageIndex, pageSize, bookName, bookTypevalue);
        // 获取总条数
        int allBookinfos = bookInfoService.findLength();
        // 加条件查询总条数
        List<BookInfo> AllqueryBookinfoByKeyWords = bookInfoService.queryBookinfoByKeyWords(0, allBookinfos, bookName, bookTypevalue);
        int listSize = AllqueryBookinfoByKeyWords.size();
        HashMap<String, Object> result = new HashMap<>();
        result.put("data", queryBookinfoByKeyWordsInPage);
        result.put("total", listSize);
        response.getWriter().write(JSONObject.toJSONString(result));
        return result;
    }

}
